package com.yanqu.road.dao.impl.activity.firework;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.activity.newyear2023.cross.CrossFireWorkUserData;
import com.yanqu.road.entity.activity.newyear2023.cross.RedPacketTable;
import com.yanqu.road.entity.activity.newyear2023.cross.RobRedPacketUser;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossFireWorkDaoImpl extends TempDao {


    public boolean addRedPacketTableList(List<RedPacketTable> list) {
        boolean result = false;
        getDb().setConnName(DbNameStrategy.getCross2Db());
        String sql = "INSERT INTO t_c_activity_firework_redpacket(activityId,no,userId,serverId,robRedPacketData,status,openTime,overTime,value,remainValue,updateTime,message)" +
                " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (RedPacketTable data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getNo()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));
            para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getRobUserMap())));
            para.put(i++, new DbParameter(Types.INTEGER, data.getStatus()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getOpenTime()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getOverTime()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getValue()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getRemainValue()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));
            para.put(i++, new DbParameter(Types.VARCHAR, data.getMessage()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }

    public boolean updateRedPacketTableList(List<RedPacketTable> list) {
        boolean result = false;
        String sql = "UPDATE t_c_activity_firework_redpacket SET robRedPacketData=?,status=?,overTime=?,remainValue=?,updateTime=?" +
                " WHERE activityId=? and userId = ? AND no=?";
        getDb().setConnName(DbNameStrategy.getCross2Db());
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (RedPacketTable data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getRobUserMap())));
            para.put(i++, new DbParameter(Types.INTEGER, data.getStatus()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getOverTime()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getRemainValue()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));

            para.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getNo()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }

    public Map<Long,Map<Integer, RedPacketTable>> getRedPacketTableMap(int activityId) {
        Map<Long,Map<Integer, RedPacketTable>> dataMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_c_activity_firework_redpacket WHERE activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++,activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                RedPacketTable data = initRedPacketTable(rs);
                if(!dataMap.containsKey(data.getUserId())){
                    dataMap.put(data.getUserId(),new ConcurrentHashMap<>());
                }
                dataMap.get(data.getUserId()).put(data.getNo(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    private RedPacketTable initRedPacketTable(ResultSet rs) throws SQLException {
        RedPacketTable data = new RedPacketTable();
        data.setActivityId(rs.getInt("activityId"));
        data.setServerId(rs.getLong("serverId"));
        data.setUserId(rs.getLong("userId"));
        data.setNo(rs.getInt("no"));
        data.setStatus(rs.getInt("status"));
        data.setOpenTime(rs.getLong("openTime"));
        data.setOverTime(rs.getLong("overTime"));
        data.setValue(rs.getInt("value"));
        data.setRemainValue(rs.getInt("remainValue"));
        data.setUpdateTime(rs.getLong("updateTime"));
        data.setMessage(rs.getString("message"));
        String str  = rs.getString("robRedPacketData");
        if(!StringUtils.isNullOrEmpty(str)){
            Map<Long, RobRedPacketUser> result = JSON.parseObject(str, new TypeReference<Map<Long, RobRedPacketUser>>() {});
            if(result != null){
                data.setRobUserMap(result);
            }
        }
        return data;
    }

    public boolean addUserDataList(List<CrossFireWorkUserData> list) {
        boolean result = false;
        getDb().setConnName(DbNameStrategy.getCross2Db());
        String sql = "INSERT INTO t_c_activity_firework_user_data(activityId,userId,serverId,tableCount,robCount,updateTime)" +
                " VALUES(?,?,?,?,?,?)";
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (CrossFireWorkUserData data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getTableCount()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getRobCount()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }

    public boolean updateUserDataList(List<CrossFireWorkUserData> list) {
        boolean result = false;
        String sql = "UPDATE t_c_activity_firework_user_data SET tableCount=?,robCount=?,updateTime=?" +
                " WHERE activityId=? and userId = ?";
        getDb().setConnName(DbNameStrategy.getCross2Db());
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (CrossFireWorkUserData data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.INTEGER, data.getTableCount()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getRobCount()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));

            para.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }

    public Map<Long, CrossFireWorkUserData> getUserDataMap(int activityId) {
        Map<Long,CrossFireWorkUserData> dataMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_c_activity_firework_user_data WHERE activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++,activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossFireWorkUserData data = initUserData(rs);
                dataMap.put(data.getUserId(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    private CrossFireWorkUserData initUserData(ResultSet rs) throws SQLException {
        CrossFireWorkUserData data = new CrossFireWorkUserData();
        data.setActivityId(rs.getInt("activityId"));
        data.setServerId(rs.getLong("serverId"));
        data.setUserId(rs.getLong("userId"));
        data.setTableCount(rs.getInt("tableCount"));
        data.setRobCount(rs.getInt("robCount"));
        data.setUpdateTime(rs.getLong("updateTime"));
        return data;
    }

    //从0开始不是1
    public int getMaxTableIndex(int activityId) {
        String getMaxIdSql = "select ifnull(max(`no`),-1) as maxId FROM t_c_activity_firework_redpacket WHERE activityId = ?";
        ResultSet rs = null;
        CallableStatement call = null;
        int maxId = -1;
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(getMaxIdSql);
            int i = 1;
            call.setInt(i++,activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                maxId = rs.getInt("maxId");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return maxId;
    }
}
